package cn.fz.luck.saas.controller;

import cn.fz.luck.saas.bean.input.SysUserInputDTO;
import cn.fz.luck.saas.config.exception.ServerException;
import cn.fz.luck.saas.config.security.jwt.JwtAuthResponse;
import cn.fz.luck.saas.model.SysUser;
import cn.fz.luck.saas.service.AuthService;
import cn.fz.luck.saas.util.DTOConvert;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;

import java.net.URI;

/**
 * JWT-认证控制层
 * @author zhuangqi
 * @date 2017/7/6.
 */
@RestController
public class AuthController {

    @Value("${jwt.header}")
    private String tokenHeader;

    @Autowired
    private AuthService authService;

    @PostMapping(value = "${jwt.route.authentication.path}")
    public ResponseEntity<?> createAuthenticationToken(@RequestParam(required = true) String userName,
                                                       @RequestParam(required = true) String password) throws ServerException{
        final String token = authService.login(userName, password);
        return ResponseEntity.ok(new JwtAuthResponse(token));
    }

    @PostMapping(value = "${jwt.route.authentication.register}")
    public  ResponseEntity<?> register(@RequestBody SysUserInputDTO userInputDTO) throws ServerException{
        SysUser user = DTOConvert.change(SysUser.class,userInputDTO);
        authService.register(user);
        return ResponseEntity.noContent().build();
    }

    @PostMapping(value = "${jwt.route.authentication.refresh}")
    public ResponseEntity<?> refresh(@RequestParam(required = true) String oldToken) throws ServerException{
        String newToken = authService.refresh(oldToken);
        return ResponseEntity.ok(new JwtAuthResponse(newToken));
    }
}
